package oamListener;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import myhistory.History;
import myhistory.HistoryDao;
import oamMyvisit.Visitor;
import oamMyvisit.VisitorDao;

/**
 * Application Lifecycle Listener implementation class MyListener
 *
 */
@WebListener
public class MyListener implements ServletContextListener, HttpSessionListener, ServletRequestListener {

	HttpServletRequest request;
	
    /**
     * Default constructor. 
     */
    public MyListener() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
	 */
	public void requestInitialized(ServletRequestEvent sre)  { 
	     // TODO Auto-generated method stub
		request=(HttpServletRequest) sre.getServletRequest();
		
		History history=new History();
		
		history.setVisittime(new Date());
		history.setUrl(request.getRequestURI().toString());
		
		HttpSession session=request.getSession();	//从session中获得id
		Visitor v=(Visitor) session.getAttribute("USER");
		history.setVisitId(v.getId());	//得到访问者的id
		
		try {
			HistoryDao dao=new HistoryDao();
			dao.saveHistory(history);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     */
    public void requestDestroyed(ServletRequestEvent sre)  { 
         // TODO Auto-generated method stub
    }

	/**
	     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
	     */
	    public void sessionCreated(HttpSessionEvent se)  { 
	         // TODO Auto-generated method stub  	
	    	//System.out.println("session--seccess");
	    	
	    	HttpSession session=se.getSession();
	    	session.setMaxInactiveInterval(10);		//设置tomcat的时间
	    	Visitor v=new Visitor();
	    	v.setIp(request.getRemoteAddr());
	    	v.setComeFrom(request.getHeader("Referer"));
	    	v.setVisitTime(new Date());
	    	
	    		    	
	///保存在数据库中
	    	
    		int id=0;
	    	try {
				VisitorDao dao=new VisitorDao();
				id=dao.saveVisitor(v);
			} catch (NamingException | SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	v.setId(id);
	    	
	    	
	///保存在在线列表中
	    	
	    	//拿到application
	    	ServletContext application =se.getSession().getServletContext();
	    	
	    	@SuppressWarnings("unchecked")
	    	//从application中得到空的map
			HashMap<String,Visitor> map=(HashMap<String, Visitor>) application.getAttribute("ONLINE");
	    	
	    	map.put(session.getId(), v);	//得到用户进来系统分配的id，并将所得信息存入v
	    	//application.setAttribute("ONLINE", map); 	//多余。因为引用，都同时修改
	    	session.setAttribute("USER", v);
	    	
	    	
	    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent se)  { 
         // TODO Auto-generated method stub
   
    	
    ///在线列表中删除离开的用户
    	
    	//从application中取出，再在HashMap<>中查询匹配，后将离开时间记录。最后在在线列表中删除
    	
    	//拿到application
    	ServletContext application = se.getSession().getServletContext();
    	
    	@SuppressWarnings("unchecked")
    	//得到application中的信息
		HashMap<String,Visitor> map=(HashMap<String, Visitor>) application.getAttribute("ONLINE");
    	String id = se.getSession().getId();
    	Visitor v=map.get(id);	//从map中拿到当前的id
    	v.setLeftTime(new Date());	//再次更新时间
    	try {
			VisitorDao dao=new VisitorDao();
			dao.updateVisitor(v);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	//在在线列表中删除离开的id
    	map.remove(id);
    	//application.setAttribute("ONLINE", map);	//多余。因为引用，都同时修改
    	
    }

	/**
	 * @see ServletContextListener#contextInitialized(ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce)  { 
	     // TODO Auto-generated method stub
		//System.out.println("application--seccess");
		
		//在服务器启动时，新建一个空的HashMap<>	每次需要用application时，需要拿它出来
		HashMap<String,Visitor> map=new HashMap<String,Visitor>();
		ServletContext application = sce.getServletContext();
		application.setAttribute("ONLINE", map);
				
	}

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce)  { 
         // TODO Auto-generated method stub
    }
	
}
